package com.asset.dispoal.user.service.commom;

import com.asset.dispoal.departmentUser.domain.db.entity.SysDepartmentUser;
import com.asset.dispoal.departmentUser.domain.db.mapper.SysDepartmentUserMapper;
import com.asset.dispoal.user.domain.db.entity.SysUserDo;
import com.asset.dispoal.user.domain.db.mapper.SysUserMapper;
import com.asset.dispoal.user.dto.UserRequest;
import com.asset.dispoal.user.service.converter.UserConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

/**
 * @author qr
 * @date 2022/4/8$
 */
@Component
public class UpdateUserCommand implements BaseCommand<UserRequest, Result> {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysDepartmentUserMapper sysDepartmentUserMapper;

    @Override
    @Transactional
    public Result<String> execute(UserRequest userRequest) {
        SysUserDo sysUserDo = UserConverter.INSTANCE.reqToDo(userRequest);

        sysUserMapper.update(sysUserDo);
        if (CollectionUtil.isNotEmpty(userRequest.getDepIds())) {
            sysDepartmentUserMapper.deleteByUser(sysUserDo.getId());
            SysDepartmentUser sysDepartmentUser = new SysDepartmentUser();
            sysDepartmentUser.setDepartmentId(userRequest.getDepIds());
            sysDepartmentUser.setUserId(sysUserDo.getId());
            sysDepartmentUserMapper.saveBatch(sysDepartmentUser);
        }

        if (CollectionUtil.isNotEmpty(userRequest.getRoleIds())) {
            sysUserMapper.deleteUserRoleByUser(sysUserDo.getId());
            sysUserMapper.saveBatchUserRole(sysUserDo.getId(), userRequest.getRoleIds());
        }
        return Result.ok();
    }
}
